/*
 * File Name：MultyView.java
 * Copyright：Copyright 2008-2014 CiWong.Inc. All Rights Reserved.
 * Description： MultyView.java
 * Modify By：res-zwyan
 * Modify Date：2014-9-13
 * Modify Type：Add
 */
package com.ciwong.mobilelib.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.URLUtil;
import android.widget.ImageView;

import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.mobilelib.R;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

/**
 * 朋友圈多图控件
 * 
 * @author res-zwyan
 * @version ciwong v.1.0 2014-9-13
 * @since ciwong v.1.0
 */
public class MultyPicView extends ViewGroup
{
    public final static int LINE_MAX_COUNT = 4;

    public int lineMaxCount = LINE_MAX_COUNT;// 每行最大图片数

    // private static final int MAX_IMG_COUNT = 9;

    public static DisplayImageOptions options = BaseConstants
            .getDisplayBuilder().cacheOnDisk(true)
            .showImageOnFail(R.mipmap.lib_default_rect_failed)
            .showImageOnLoading(R.mipmap.lib_default_rect)
            .showImageForEmptyUri(R.mipmap.lib_default_rect_failed)
            .bitmapConfig(Bitmap.Config.ARGB_8888).cacheInMemory(true)
            .imageScaleType(ImageScaleType.IN_SAMPLE_INT).build();

    static ImageLoader loader = ImageLoader.getInstance();

    /**
     * 图片地址
     */
    String[] imgUrls;

    /**
     * 图片的数量
     */
    private int mImgCount;

    int space = 5;

    /**
     * 子view边长度
     */
    private int mChildEdgeSize;

    /**
     * 子view可见个数
     */
    private int mChildVisibleCount;

    private int mMaxChildCount = 9;

    // private String tempThumbnailsuffix = Utils
    // .getThumbnailSuffix(ThumbnailSuffixStr._150_150);

    // private String thumbnailsuffix = tempThumbnailsuffix;

    /**
     * 习信空间发的图片
     */
    private static String web_thumbnailsuffix = "/150";

    private boolean mIntercept = false;

    private static final int minImgSize = 20;

    /**
     * 服务器上缩略图最大尺寸
     */
    private static final int maxPicSize = 250;

    /**
     * View.INVISIBLE View.GONE
     * 
     * @author res-zwyan
     */
    public static enum Mode
    {
        INVISIBLE, GONE
    }

    /**
     * 单张图片宽度
     */
    private int sigleSrcWidth;

    /**
     * 单张图片高度
     */
    private int sigleSrcHeight;

    /**
     * 单张图片时控件期望的边的最大的大小
     */
    private int sigleExpectMaxViewSize;

    private float sigleExpectMaxViewRatio = 1f;

    /**
     * 单张图片时图片缩放比例
     */
    private float sigleScaleRatio;

    /**
     * visible gone 默认用visible
     */
    private Mode mCurrentMode = Mode.GONE;

    private ClickCallback mClickCallback;

    OnClickListener clickListener = new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            if (v instanceof ImageView)
            {
                Integer index = (Integer) v.getTag();

                // String[] imgUrlArray = null;
                // imgUrlArray = FCUtil.addTokenForAllPic(imgUrls);
                if (mClickCallback != null)
                {
                    mClickCallback.callback(index, imgUrls);
                }
            }

        }
    };

    public MultyPicView(Context context)
    {
        super(context);
    }

    public MultyPicView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
                R.styleable.multy_pic_view, 0, 0);

        int n = a.getIndexCount();

        for (int i = 0; i < n; i++)
        {
            int attr = a.getIndex(i);

            if (attr == R.styleable.multy_pic_view_picSpace)
            {
                float mul = a.getFloat(attr, 1.0f);
                space = DeviceUtils.dip2px(mul);
            }
        }
        sigleExpectMaxViewSize = Math.min(DeviceUtils.getScreenHeight(),
                DeviceUtils.getScreenWdith());
        sigleExpectMaxViewSize = (int) (sigleExpectMaxViewSize
                * sigleExpectMaxViewRatio);
        a.recycle();
    }

    /**
     * 设置缩略图大小 默认是 150 * 150
     * 
     * @param thumbnailsuffix
     *            缩略图后缀
     */
    public void setThumbnailsuffix(int thumbnailsuffix)
    {
        // this.tempThumbnailsuffix = Utils.getThumbnailSuffix(thumbnailsuffix);
    }

    public void setMaxChildCount(int len)
    {

        removeAllViews();
        mMaxChildCount = len;

        for (int i = 0; i < len; i++)
        {
            ImageViewChangeBg iv = new ImageViewChangeBg(getContext());
            LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            iv.setOnClickListener(clickListener);
            iv.setTag(i);
            this.addView(iv, params);
        }
    }

    /**
     *
     * @param mode
     */
    public void setMode(Mode mode)
    {
        mCurrentMode = mode;
    }

    public String[] getImgUrl()
    {
        return imgUrls;
    }

    /**
     * 是否符合单张图片
     * 
     * @param imgs
     *            图片个数
     * @return 是否符合
     */
    private boolean isSingleImg(String[] imgs)
    {
        if (imgs != null && imgs.length == 1)
        {
            return true;
        }
        return false;
    }

    // /**
    // * 检测是否显示原图
    // * @param oriWidth 原图宽度
    // * @param oriHeight 原图高度
    // * @param viewWidth 控件宽度
    // * @param viewHeight 控件高度
    // * @return true 显示原图 false 不显示原图
    // */
    // private boolean checkIsShowOriginPic(int oriWidth,int oriHeight,int
    // viewWidth,int viewHeight)
    // {
    // int oriMaxSize = Math.max(oriWidth,oriHeight);
    // float oriRatio = 1.0f;
    // if(oriMaxSize > maxPicSize)
    // {
    // oriRatio = oriMaxSize/maxPicSize;
    // }
    // oriWidth = oriWidth / oriRatio;
    // oriHeight = oriWidth / oriRatio;
    // }

    /**
     * 单张图时调用
     * 
     * @param imgUrl
     * @param srcWidth
     * @param srcHeight
     */
    public void setSingleImg(String imgUrl, int srcWidth, int srcHeight)
    {
        lineMaxCount = 1;
        int maxSize = Math.max(srcWidth, srcHeight);
        sigleScaleRatio = 1f;
        if (maxSize > sigleExpectMaxViewSize)
        {
            sigleScaleRatio = maxSize * 1.0f / sigleExpectMaxViewSize;
        }

        sigleSrcWidth = (int) (srcWidth / sigleScaleRatio);
        sigleSrcHeight = (int) (srcHeight / sigleScaleRatio);
        CWLog.d("mul", "sigleSrcWidth =" + sigleSrcWidth + " sigleSrcHeight="
                + sigleSrcHeight);
        boolean request = false;
        imgUrls = new String[]{imgUrl};
        if (imgUrls != null && imgUrls.length == 1)
        {
            request = true;
        }
        dealWithImgs(imgUrls);
        if (request)
        {
            this.requestLayout();
        }
    }

    public void setImgs(String[] imgs)
    {
        lineMaxCount = LINE_MAX_COUNT;
        CWLog.d("mul", "setimgs len = " + imgs.length);
        sigleSrcHeight = sigleSrcWidth = 0;
        sigleScaleRatio = 1;
        // thumbnailsuffix =
        // Utils.getThumbnailSuffix(ThumbnailSuffixStr._150_150);
        dealWithImgs(imgs);
    }

    private void dealWithImgs(String[] imgs)
    {
        if (imgs == null || imgs.length == 0)
        {
            return;
        }
        // if (isSingleImg(imgs))
        // {
        // thumbnailsuffix = "";
        // 单图直接用250x250
        // if (sigleScaleRatio >= 3.5f)
        // {
        // }
        // else
        // {
        // thumbnailsuffix = Utils
        // .getThumbnailSuffix(ThumbnailSuffixStr._250_250);
        // }
        // }
        // else
        // {
        // thumbnailsuffix = tempThumbnailsuffix;
        // }
        imgUrls = imgs;
        mImgCount = imgs.length;
        int imgLen = mImgCount;
        Mode currentMode = mCurrentMode;
        int maxChildCount = mMaxChildCount;
        for (int i = 0; i < maxChildCount; i++)
        {
            final ImageView chileIv = (ImageView) getChildAt(i);
            if (i < imgLen)
            {
                chileIv.setVisibility(View.VISIBLE);
                // chileIv.setImageResource(R.drawable.grey);//默认图片
                String url = getUrl(imgs[i]);
                ImageSize imageSize = null;
                if (i == 0 && mImgCount == 1 && sigleSrcWidth != 0
                        && sigleSrcWidth != 0)
                {
                    // LayoutParams params = chileIv.getLayoutParams();
                    // params.height = sigleSrcHeight;
                    // params.width = sigleSrcWidth;
                    imageSize = new ImageSize(sigleSrcWidth, sigleSrcHeight);
                }
                else
                {
                    imageSize = new ImageSize(maxPicSize, maxPicSize);
                }
                loader.loadImage(url, imageSize, options,
                        new ImageLoadingListener()
                        {
                            @Override
                            public void onLoadingStarted(String s, View view)
                            {

                            }

                            @Override
                            public void onLoadingFailed(String s, View view,
                                    FailReason failReason)
                            {

                            }

                            @Override
                            public void onLoadingComplete(String s, View view,
                                    Bitmap bitmap)
                            {
                                if (chileIv != null)
                                {
                                    chileIv.setImageBitmap(bitmap);
                                }
                            }

                            @Override
                            public void onLoadingCancelled(String s, View view)
                            {

                            }
                        });
            }
            else
            {
                if (currentMode == Mode.INVISIBLE)
                {
                    chileIv.setVisibility(View.INVISIBLE);
                }
                else
                {
                    chileIv.setVisibility(View.GONE);
                }
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        if (getChildCount() == 0)
        {
            setMaxChildCount(mMaxChildCount);
        }
        measureImgWidth(widthMeasureSpec);
        mChildVisibleCount = getVisibleChildCount();
        int lines = getMulitImgLines(mChildVisibleCount);
        int viewHeight = ((lines - 1) * space + lines * mChildEdgeSize)
                + getPaddingTop() + getPaddingBottom();
        if (mImgCount == 1)
        {
            viewHeight = sigleSrcHeight == 0 ? viewHeight : sigleSrcHeight;
        }
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        CWLog.d("mul",
                "widthSize =" + widthSize + " viewHeight =" + viewHeight);
        setMeasuredDimension(widthSize, viewHeight);

        int heightSize = mChildEdgeSize;
        widthSize = heightSize;
        if (mImgCount == 1 && sigleSrcWidth != 0)
        {
            widthSize = sigleSrcWidth;
            heightSize = sigleSrcHeight;
        }
        CWLog.d("mul", "chld size = widthSize =" + widthSize + " viewHeight ="
                + viewHeight);

        measureChildren(widthSize, heightSize);
    }

    protected void measureImgWidth(int widthMeasureSpec)
    {
        if (mChildEdgeSize == 0)
        {
            int measureSize = MeasureSpec.getSize(widthMeasureSpec);

            mChildEdgeSize = (measureSize - (lineMaxCount - 1) * space
                    - getPaddingLeft() - getPaddingRight()) / lineMaxCount;
        }
    }

    /**
     * 判断是否是窄图
     * 
     * @param height
     *            图片缩放后的高
     * @param width
     *            图片缩放后的宽
     * @return true 是窄图 false 不是窄图
     */
    private static boolean checkImgIsNarrow(int height, int width)
    {
        if (height <= minImgSize || width <= minImgSize)
        {
            return true;
        }
        return false;
    }

    /**
     * 设置是否截获事件
     * 
     * @param intercept
     *            true 截获
     */
    public void setIntercept(boolean intercept)
    {
        mIntercept = intercept;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev)
    {
        return mIntercept;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {

        int lpadding = getPaddingLeft();
        int tpadding = getPaddingTop();
        int left = lpadding, top = tpadding;
        int childCount = getChildCount();
        int visibleChildCount = mChildVisibleCount;
        int breakLineC = 0; // 断行
        // if (visibleChildCount == 4)
        // {
        // breakLineC = 2;
        // }
        // else
        // {
        breakLineC = lineMaxCount;
        // }
        for (int i = 0; i < childCount; i++)
        {
            View child = getChildAt(i);
            if (child.getVisibility() == View.GONE)
            {
                continue;
            }
            if (visibleChildCount == 1)
            {
                // 单张做特殊显示
                if (lineMaxCount == 1)
                {
                    left = (getMeasuredWidth() - sigleSrcWidth) / 2;// 居中
                    CWLog.i("multy", left + "");
                }
                if (sigleSrcWidth == 0 || sigleSrcHeight == 0)
                {
                    child.layout(left, top, left + mChildEdgeSize,
                            top + mChildEdgeSize);
                }
                else
                {
                    child.layout(left, top, left + sigleSrcWidth,
                            top + sigleSrcHeight);
                }
            }
            else
            {
                child.layout(left, top, left + mChildEdgeSize,
                        top + mChildEdgeSize);
                left += (space + mChildEdgeSize);
                if ((i + 1) % breakLineC == 0)
                {
                    top += mChildEdgeSize + space;
                    left = lpadding;
                }
            }
        }
    }

    private int getVisibleChildCount()
    {
        int childCount = getChildCount();
        int count = 0;
        for (int i = 0; i < childCount; i++)
        {
            if (getChildAt(i).getVisibility() != View.GONE)
            {
                count++;
            }
        }
        return count;
    }

    public void setClickCallback(ClickCallback callback)
    {
        mClickCallback = callback;
    }

    /**
     * 点击图片回调
     * 
     * @author RES-KUNZHU
     * 
     */
    public interface ClickCallback
    {
        /**
         * 回调方法
         * 
         * @param index
         *            点击的索引
         * @param str
         *            图片地址数组
         */
        void callback(int index, String[] str);
    }

    public int getMulitImgLines(int imgSize)
    {
        if (imgSize == 0)
        {
            return 1;
        }
        return (imgSize + lineMaxCount - 1) / lineMaxCount;
    }

    /**
     * 获取当前图片数量
     * 
     * @return 数量
     */
    public int getImgCount()
    {
        return mImgCount;
    }

    /**
     * 获取url
     * 
     * @param url
     * @return
     */
    private String getUrl(String url)
    {
        if (URLUtil.isHttpsUrl(url) || URLUtil.isHttpUrl(url))
        {

            // if (url.contains(TPRequestUtilFC.NONEEDDELFILES))
            // {
            // url += thumbnailsuffix;
            // }
            // else
            // {
            // if (url.contains(TPRequestUtilFC.IMG1URL))
            // {
            // url += web_thumbnailsuffix;
            // }
            // }
            // url = TPRequestUtil.handlerPicUrl(url);
        }
        else
        {
            if (url != null && url.indexOf(BaseConstants.FILE_PREFIX) == -1)
            {
                url = BaseConstants.FILE_PREFIX + url;
            }
        }
        return url;
    }

}
